package cn.tedu.ivos.base.file;

import cn.tedu.ivos.base.response.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Tag(name = "图片上传模块")
@Slf4j
@RestController
@RequestMapping("/v1/file")
public class UploadController {
	
	@Operation(summary = "图片上传功能")
	@ApiOperationSupport(order = 10)
	@PostMapping("upload")
	public JsonResult upload(MultipartFile file) throws IOException {
		log.debug("图片上传,参数={}",file);
		//1.获取当前上传的原始图片名
		String fileName = file.getOriginalFilename();
		//2.截取文件后缀名
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		//3.生成一个不会重复的新文件名
		fileName = UUID.randomUUID()+suffix;
		//4.指定一个目录用来存储上传的图片文件
		String dirPath = "d:/files";
		//5.将当前日期转为多层文件夹路径的格式
		SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
		String datePath = sdf.format(new Date());
		//6.准备一个文件类对象,创建多层文件夹
		File dirFile = new File(dirPath+datePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		//7.将图片存入上方创建好的多层文件夹中
		String filePath = dirPath+datePath+fileName;
		file.transferTo(new File(filePath));
		//8.返回图片上传成功的响应结果
		return JsonResult.ok(datePath+fileName);
	}
	
	@Operation(summary = "图片删除功能")
	@ApiOperationSupport(order = 20)
	@PostMapping("remove")
	public JsonResult remove(String imgUrl){
		log.debug("图片删除,参数={}",imgUrl);
		new File("d:/files"+imgUrl).delete();
		return JsonResult.ok();
	}
	
	
	
}
